<script setup lang="ts">
import { ref, onMounted } from 'vue'
import type { commentData, commentListData } from '@/utils/interface'
import { getCommentTime, getTimeYMDHMS } from '@/utils/time';
import { addCommentApi } from '@/api/comments_api';
import { getCommentByArticleIdApi, complaintCommentApi } from '@/api/comments_api';
import { useCode } from '@/hooks/codeHook';
import { ElMessage } from 'element-plus'
const { tackleCode } = useCode();

const props = defineProps({
    article_id: {
        type: Number,
        default: 0
    }
})


const commentContent = ref<string>('') //评论输入框内容
const commentKidsContent = ref<string>('') //子评论输入框列表
const commentCount = ref(0) //评论总数
const listQuery = ref<any>({
    pageSize: 10,
    nowPage: 1,
})

// 表情包相关
const showEmojiPicker = ref(false) // 显示表情选择器
const showEmojiPickerKids = ref(false) // 子评论显示表情选择器

// 常用表情包列表
const emojiList = [
  ['😀', '😃', '😄', '😁', '😆', '😅', '😂', '🤣', '😊', '😇'],
  ['😉', '😌', '😍', '🥰', '😘', '😗', '😙', '😚', '😋', '😛'],
  ['😝', '😜', '🤪', '🤨', '🧐', '🤓', '😎', '🤩', '🥳', '😏'],
  ['😒', '😞', '😔', '😟', '😕', '🙁', '☹️', '😣', '😖', '😫'],
  ['😩', '🥺', '😢', '😭', '😤', '😠', '😡', '🤬', '🤯', '😳'],
  ['🥵', '🥶', '😱', '😨', '😰', '😥', '😓', '🤗', '🤔', '🤭'],
  ['🤫', '🤥', '😶', '😐', '😑', '😬', '🙄', '😯', '😦', '😧'],
  ['😮', '😲', '🥱', '😴', '🤤', '😪', '😵', '🤐', '🥴', '🤢']
]

// 插入表情到输入框
const insertEmoji = (emoji: string, isKids: boolean = false) => {
  if (isKids) {
    commentKidsContent.value += emoji
  } else {
    commentContent.value += emoji
  }
  // 关闭表情选择器
  showEmojiPicker.value = false
  showEmojiPickerKids.value = false
}

// 切换表情选择器显示状态
const toggleEmojiPicker = (isKids: boolean = false) => {
  if (isKids) {
    showEmojiPickerKids.value = !showEmojiPickerKids.value
    showEmojiPicker.value = false
  } else {
    showEmojiPicker.value = !showEmojiPicker.value
    showEmojiPickerKids.value = false
  }
}
const commentList = ref<commentListData[]>([]) //一级评论列表
const commentKidsList = ref<commentListData[]>([]) //二、三级评论列表
//发布评论
const addComment = async (root_id: number, parent_id: number) => {
    try {
        const res = await addCommentApi({
            user_id: '0',
            user_type: 0,
            user_name: '游客',
            article_id: props.article_id,
            created_at: getTimeYMDHMS(new Date()),
            content: commentContent.value || commentKidsContent.value,
            root_id: root_id,
            parent_id: parent_id,
        })
        if (res.data.code === 200) {
            // 清空输入框
            commentKidsContent.value = '';
            commentContent.value = '';
            getComment();
        }
    } catch (error) {
        console.log('addComment error', error);
    }
}
//获取评论
const getComment = async () => {
    try {
        const res = await getCommentByArticleIdApi({
            ...listQuery.value,
            article_id: props.article_id,
            count: true
        })
        if (tackleCode(res.data.code)) {
            commentList.value = res.data.result.filter((item: commentData) => (
                item.root_id === 0))
            commentKidsList.value = res.data.result.filter((item: commentData) => (
                item.root_id !== 0))
            // 获取一级评论的子评论数量
            commentList.value.forEach((item: commentListData) => {
                item.KidsNum = res.data.result.filter((kid: commentData) => (
                    kid.root_id === item.id
                )).length
            })
            commentCount.value = res.data.count
        }
    } catch (error) {
        console.log('getComment error', error);
    }
}
// 处理子评论列表（把子评论列表赋值给一级评论项）、打开列表
const getKidsList = (root_id: number) => {

    commentList.value.forEach((item: commentListData) => {
        if (item.id === root_id) {
            item.isOpenCommentKids = !item.isOpenCommentKids
            item.KidsList = commentKidsList.value.filter((kid: commentListData) => (
                kid.root_id === root_id
            ))
        }
    })
}
// 点击显示回复框
const clickReply = (item: commentListData) => {
    console.log(commentList.value);
    // 遍历所有一级评论
    commentList.value.forEach(parentComment => {
        //筛选出不是当前点击项的一级评论，然后关闭其他的回复框
        if (item.id !== parentComment.id) {
            parentComment.isOpenReply = false;
        }
        if (parentComment.KidsList) {
            parentComment.KidsList.forEach(kidComment => {
                //筛选出不是当前点击项的二级评论，然后关闭其他的回复框
                if (item.id !== kidComment.id) {
                    kidComment.isOpenReply = false;
                }
            });
        }
    });
    // 第二步：切换当前点击评论项的回复框显示状态
    item.isOpenReply = !item.isOpenReply;
}
//返回回复用户id的字符串且高亮显示
const getReplyUserId = (item: commentListData) => {
    return `回复<span class="text-blue-500 font-bold">@${item.user_name}${item.parent_id}</span>: `;
}

// 防抖函数
function debounce<T extends (...args: any[]) => any>(
    func: T,
    wait: number,
): (...args: Parameters<T>) => void {
    let timeout: number | null = null;

    return function (this: any, ...args: Parameters<T>) {
        if (timeout) clearTimeout(timeout);
        timeout = window.setTimeout(() => {
            func.apply(this, args);
        }, wait);
    };
}
// 评论的举报加一
const complaintComment = async (id: number) => {
    try {
        const res = await complaintCommentApi({
            id: id,
        })
        if (tackleCode(res.data.code)) {
            ElMessage.primary('感谢您的举报，举报信息成功发送至站主。')
        }
    } catch (error) {
        console.log('complaintComment error', error);
    }
}
// 防抖版本 - 适用于连续点击场景，最后一次点击后延迟执行
const debouncedComplaintComment = debounce((id: number) => {
    complaintComment(id);
}, 1000);


onMounted(() => {
    console.log(props.article_id);
    getComment()
})

</script>

<template>
    <div>
        <!-- top -->
        <div class="text-2xl font-bold text-slate-800 mb-6 flex items-center">
            <i class="mr-2">💬</i> 评论
            <span v-if="commentList.length > 0" class="">
                {{ commentCount }}
            </span>
        </div>
        <!-- 一级输入框 -->
        <div class="relative flex items-start gap-4 p-4 border border-slate-100 rounded-xl bg-slate-50 ">
            <img src="/blog-logo.png" alt="用户头像"
                class="w-12 h-12 rounded-full object-cover border-2 border-white shadow-md transition-transform duration-300 hover:scale-105">
            <div class="flex-1 flex flex-col gap-3">
                <div class="relative">
                    <textarea placeholder="写下您的评论..." rows="4" v-model="commentContent"
                        class="w-full px-4 py-3 bg-white border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-400 focus:border-transparent transition-all duration-200 text-slate-700 resize-none"></textarea>
                    <!-- 表情按钮 -->
                    <button @click="toggleEmojiPicker(false)" 
                        class="absolute left-3 bottom-3 p-1.5 bg-slate-100 hover:bg-slate-200 rounded-full transition-colors duration-200 z-10">
                        <span class="text-lg">😊</span>
                    </button>
                </div>
                
                <!-- 表情选择器 -->
                <div v-if="showEmojiPicker" class="absolute top-full left-0 mt-2 bg-white border border-slate-200 rounded-lg shadow-xl z-50"
                     style="width: 320px; height: 280px;">
                    <div class="flex justify-between items-center p-4 border-b border-slate-100">
                        <span class="text-sm font-medium text-slate-700">选择表情</span>
                        <button @click="showEmojiPicker = false" class="text-slate-400 hover:text-slate-600 p-1">
                            ✕
                        </button>
                    </div>
                    <div class="overflow-y-auto h-[232px] p-4">
                        <div v-for="(row, rowIndex) in emojiList" :key="rowIndex" class="flex justify-center gap-2 mb-2">
                            <button v-for="emoji in row" :key="emoji" 
                                @click="insertEmoji(emoji, false)"
                                class="text-xl p-2 hover:bg-slate-100 rounded-lg transition-colors duration-200 transform hover:scale-110">
                                {{ emoji }}
                            </button>
                        </div>
                    </div>
                </div>
                
                <div class="flex justify-between items-center" v-show="commentContent.length > 0">
                    <div class="flex items-center text-sm text-slate-500">
                        <span class="mr-2">💡</span>
                        <span>点击表情按钮添加表情</span>
                    </div>
                    <button @click="addComment(0, 0)"
                        class="px-6 py-2 bg-blue-600 text-white font-medium rounded-lg hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 transition-all duration-200 transform hover:translate-y-[-2px]">
                        发表评论
                    </button>
                </div>
            </div>
        </div>
        <!-- 评论内容区 -->
        <div class="w-full">
            <div v-for="item in commentList" :key="item.id" class=" w-full p-4 mb-4 flex ">
                <img src="/blog-logo.png" alt="用户头像" class="w-12 h-12 rounded-full object-covershadow-md mr-5">
                <div class=" w-full border-b border-slate-700 pb-5">
                    <div class="group">
                        <p class="text-sm text-slate-400">{{ item.user_name }}{{ item.id }}</p>
                        <p class="">{{ item.content }}</p>
                        <div class="w-full flex justify-between">
                            <div class="flex text-sm text-slate-400">
                                <p class="mr-5">{{ getCommentTime(item.created_at) }}</p>
                                <span @click="clickReply(item)" class="cursor-pointer hover:text-blue-600">回复</span>
                            </div>
                            <el-button
                                class=" cursor-pointer opacity-0 group-hover:opacity-100 transition-opacity duration-100"
                                size="small" type="text" @click="debouncedComplaintComment(item.id)">
                                <p class="text-base">举报</p>
                            </el-button>
                        </div>

                        <div v-if="item.KidsNum !== 0" class="flex">
                            <p>共{{ item.KidsNum }}条子回复,</p>
                            <p @click="getKidsList(item.id)" class="cursor-pointer hover:text-blue-600">点击查看</p>
                        </div>
                    </div>

                    <!-- 二级、三级评论列表 -->
                    <div v-if="item.isOpenCommentKids">
                        <div v-for="kid in item.KidsList" :key="kid.id" class="w-full p-4 mb-4">
                            <div class="flex">
                                <img src="/blog-logo.png" alt="用户头像"
                                    class="w-12 h-12 rounded-full object-cover shadow-md mr-5">
                                <div class="w-full group">
                                    <p class="text-sm text-slate-400">{{ kid.user_name }}{{ kid.id }}</p>
                                    <div>
                                        <p v-if="kid.parent_id === 0" class="">{{ kid.content }}</p>
                                        <p v-else class=""><span v-html="getReplyUserId(kid)"></span>{{ kid.content }}
                                        </p>
                                    </div>
                                    <div class="w-full flex justify-between">
                                        <div class="flex text-sm text-slate-400">
                                            <p class="mr-5">{{ getCommentTime(kid.created_at) }}</p>
                                            <span @click="clickReply(kid)"
                                                class="cursor-pointer hover:text-blue-600">回复</span>
                                        </div>
                                        <el-button
                                            class=" cursor-pointer opacity-0 group-hover:opacity-100 transition-opacity duration-100"
                                            size="small" type="text" @click="debouncedComplaintComment(kid.id)">
                                            <p class="text-base">举报</p>
                                        </el-button>
                                    </div>
                                </div>
                            </div>
                            <!-- 三级评论输入框 -->
                            <div v-if="kid.isOpenReply"
                                class="relative w-full flex items-start gap-4 p-4 border border-slate-100 rounded-xl bg-slate-50 mt-4">
                                <img src="/blog-logo.png" alt="用户头像"
                                    class="w-12 h-12 rounded-full object-cover border-2 border-white shadow-md transition-transform duration-300 hover:scale-105">
                                <div class="flex-1 flex flex-col gap-3">
                                    <div class="relative">
                                        <textarea :placeholder="`回复@${kid.user_name}${kid.id} :`" rows="4"
                                            v-model="commentKidsContent"
                                            class="w-full px-4 py-3 bg-white border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-400 focus:border-transparent transition-all duration-200 text-slate-700 resize-none"></textarea>
                                        <!-- 表情按钮 -->
                                        <button @click="toggleEmojiPicker(true)" 
                                            class="absolute left-3 bottom-3 p-1.5 bg-slate-100 hover:bg-slate-200 rounded-full transition-colors duration-200 z-10">
                                            <span class="text-lg">😊</span>
                                        </button>
                                    </div>
                                    
                                    <!-- 表情选择器 -->
                                    <div v-if="showEmojiPickerKids" class="absolute top-full left-0 mt-2 bg-white border border-slate-200 rounded-lg shadow-xl z-50"
                                         style="width: 320px; height: 280px;">
                                        <div class="flex justify-between items-center p-4 border-b border-slate-100">
                                            <span class="text-sm font-medium text-slate-700">选择表情</span>
                                            <button @click="showEmojiPickerKids = false" class="text-slate-400 hover:text-slate-600 p-1">
                                                ✕
                                            </button>
                                        </div>
                                        <div class="overflow-y-auto h-[232px] p-4">
                                            <div v-for="(row, rowIndex) in emojiList" :key="rowIndex" class="flex justify-center gap-2 mb-2">
                                                <button v-for="emoji in row" :key="emoji" 
                                                    @click="insertEmoji(emoji, true)"
                                                    class="text-xl p-2 hover:bg-slate-100 rounded-lg transition-colors duration-200 transform hover:scale-110">
                                                    {{ emoji }}
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="flex justify-between items-center" v-show="commentKidsContent.length > 0">
                                        <div class="flex items-center text-sm text-slate-500">
                                            <span class="mr-2">💡</span>
                                            <span>点击表情按钮添加表情</span>
                                        </div>
                                        <button @click="addComment(kid.root_id, kid.id)"
                                            class="px-6 py-2 bg-blue-600 text-white font-medium rounded-lg hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 transition-all duration-200 transform hover:translate-y-[-2px]">
                                            发表评论
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <!-- 二级评论输入框 -->
                    <div v-if="item.isOpenReply"
                        class="relative w-full flex items-start gap-4 p-4 border border-slate-100 rounded-xl bg-slate-50 mt-4">
                        <img src="/blog-logo.png" alt="用户头像"
                            class="w-12 h-12 rounded-full object-cover border-2 border-white shadow-md transition-transform duration-300 hover:scale-105">
                        <div class=" flex-1 flex flex-col gap-3">
                            <div class="relative">
                                <textarea :placeholder="`回复@${item.user_name}${item.id} :`" rows="4"
                                    v-model="commentKidsContent"
                                    class="w-full px-4 py-3 bg-white border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-400 focus:border-transparent transition-all duration-200 text-slate-700 resize-none"></textarea>
                                <!-- 表情按钮 -->
                                <button @click="toggleEmojiPicker(true)" 
                                    class="absolute left-3 bottom-3 p-1.5 bg-slate-100 hover:bg-slate-200 rounded-full transition-colors duration-200 z-10">
                                    <span class="text-lg">😊</span>
                                </button>
                            </div>
                            
                            <!-- 表情选择器 -->
                            <div v-if="showEmojiPickerKids" class="absolute top-full left-0 mt-2 bg-white border border-slate-200 rounded-lg shadow-xl z-50"
                                 style="width: 320px; height: 280px;">
                                <div class="flex justify-between items-center p-4 border-b border-slate-100">
                                    <span class="text-sm font-medium text-slate-700">选择表情</span>
                                    <button @click="showEmojiPickerKids = false" class="text-slate-400 hover:text-slate-600 p-1">
                                        ✕
                                    </button>
                                </div>
                                <div class="overflow-y-auto h-[232px] p-4">
                                    <div v-for="(row, rowIndex) in emojiList" :key="rowIndex" class="flex justify-center gap-2 mb-2">
                                        <button v-for="emoji in row" :key="emoji" 
                                            @click="insertEmoji(emoji, true)"
                                            class="text-xl p-2 hover:bg-slate-100 rounded-lg transition-colors duration-200 transform hover:scale-110">
                                            {{ emoji }}
                                        </button>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="flex justify-between items-center" v-show="commentKidsContent.length > 0">
                                <div class="flex items-center text-sm text-slate-500">
                                    <span class="mr-2">💡</span>
                                    <span>点击表情按钮添加表情</span>
                                </div>
                                <button @click="addComment(item.id, item.root_id)"
                                    class="px-6 py-2 bg-blue-600 text-white font-medium rounded-lg hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 transition-all duration-200 transform hover:translate-y-[-2px]">
                                    发表评论
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<style scoped></style>
